<!--
 * @Author: zhangyonggui
 * @Date: 2023-11-16 19:38:29
 * @LastEditors: zhangyonggui
 * @LastEditTime: 2024-01-20 10:57:29
 * @Descripttion: 
-->
<template>
  <el-dialog
    title="选择POC"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal-append-to-body="false"
    width="70%"
    top="15vh"
  >
    <div class="dialog-body">
      <el-form inline @submit.native.prevent class="search-form">
        <el-row :gutter="18">
          <el-col :span="6">
            <el-form-item label="漏洞编号:">
              <el-input
                v-model.trim="search.vul_id"
                placeholder="请输入漏洞编号"
                size="small"
                clearable
                @keyup.enter.native="searchClick"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="PoC名称:">
              <el-input
                v-model.trim="search.name"
                placeholder="请输入PoC名称"
                size="small"
                clearable
                @keyup.enter.native="searchClick"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签:">
              <el-input
                v-model.trim="search.tags"
                placeholder="请输入标签"
                size="small"
                clearable
                @keyup.enter.native="searchClick"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button class="seach-btn" size="small" @click="searchClick"
                >查询</el-button
              >
              <el-button class="seach-reset" size="small" @click="reset"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div
        class="search-table"
        v-loading="loading"
        element-loading-text="Loading"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <div class="operate-wrap">
          <el-button
            class="new-btn"
            size="small"
            :disabled="select_box.length === 0"
            @click="enable"
            >启用</el-button
          >
          <el-button
            class="new-btn"
            size="small"
            :disabled="select_box.length === 0"
            @click="disable"
            >禁用</el-button
          >
          <el-button class="new-btn" size="small" @click="allEnable">
            一键启用
          </el-button>
          <el-button class="new-btn" size="small" @click="allDisable">
            一键禁用
          </el-button>
        </div>
        <el-table
          ref="multipleTable"
          :data="pocData"
          :header-cell-style="{
            background: 'rgba(255, 255, 255, 0.07)',
            color: 'rgba(255, 255, 255, 0.9)',
            fontSize: '14px',
            fontWeight: '500',
            border: 'none',
          }"
          :cell-style="{
            background: 'transparent',
            color: 'rgba(255, 255, 255, 0.8)',
            fontSize: '12px',
            fontWeight: '500',
            borderColor: 'rgba(255, 255, 255, 0.05)',
          }"
          style="width: 100%"
          @select="selectOne"
          @select-all="selectAll"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="PoC名称" prop="pocName">
            <template #default="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row.pocName"
                placement="top"
              >
                <div class="tooltip-box">{{ scope.row.pocName }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="关联漏洞编号" prop="vulCode">
            <template #default="scope">
              <span v-if="scope.row.vulCode?.length > 0">
                <span>{{ scope.row.vulCode[0] }}</span>
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content">
                    <div
                      v-for="(item, index) in scope.row.vulCode"
                      :key="index"
                    >
                      {{ item }}
                    </div>
                  </div>
                  <span>({{ scope.row.vulCode.length }})</span>
                </el-tooltip>
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="标签" prop="tags">
            <template #default="scope">
              <span v-if="scope.row.tags?.length > 0">
                <el-tag effect="dark" size="small">{{
                  scope.row.tags[0]
                }}</el-tag>
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content">
                    <div v-for="(item, index) in scope.row.tags" :key="index">
                      {{ item }}
                    </div>
                  </div>
                  <span>({{ scope.row.tags.length }})</span>
                </el-tooltip>
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="是否启用" prop="isEnable" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isEnable"
                @change="switchChange($event, scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          size="small"
          :current-page="search.pageNumber"
          :page-size="search.pageSize"
          :page-sizes="[5, 10, 15, 20, 50, 100]"
          :layout="'total, sizes, prev, pager, next, jumper'"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button type="primary" size="small" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  defineProps,
  defineEmits,
  watch,
  onMounted,
  ref,
  reactive,
  nextTick,
} from 'vue';
import { ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
const store = useStore();
const emit = defineEmits(['update:isShow', 'confirm']);
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
  assetCount: {
    type: Number,
    default: 0,
  },
  selectType: {
    type: Number,
    default: 0,
  },
  searchData: {
    type: Object,
    default: () => {
      return {};
    },
  },
  selectedIds: {
    type: Array,
    default: () => [],
  },
});
const visible = ref(props.isShow);
const loading = ref(false);
const total = ref(0);
let search = reactive({
  pageSize: 10,
  pageNumber: 1,
  vul_id: null,
  name: null,
  tags: null,
});
const multipleTable = ref<any>(null);
const pocData = ref<any>([]);
const pocIds = ref([]); // 传给后端的id
const select_box = ref<any[]>([]);
const allPocIds = ref([]); // 所有的ID
const selectIds = ref<any>([]); // 勾选的id
const enableIds = ref<any>([]); // 已经启用的id

watch(
  () => visible.value,
  (newValue) => {
    emit('update:isShow', newValue);
  },
);

onMounted(() => {
  enableIds.value = props.selectedIds;
  getPocIds();
  getList();
});
const cancel = () => {
  visible.value = false;
};
// 单选
const selectOne = (selection: any, row: any) => {
  // isSelect true为选中 false 为取消
  let isSelect = selection.length && selection.indexOf(row) > -1;
  //findIndex返回-1则不存在，>0则存在
  let n = select_box.value.findIndex((v) => {
    return v == row.pocId;
  });
  if (isSelect) {
    if (n < 0) select_box.value.push(row.pocId);
  } else {
    if (n > -1) select_box.value.splice(n, 1);
  }
  selectIds.value = select_box.value;
};
const selectAll = (selection) => {
  //全选先把所有id拿到并去重
  let _arr = [...new Set(selection.map((res) => res.pocId))];
  select_box.value = _arr;
  selectIds.value = select_box.value;
};
const enable = () => {
  ElMessageBox.confirm('确定启用所选数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    enableIds.value.push(...selectIds.value);
    pocData.value.forEach((el: any) => {
      if (enableIds.value.includes(el.pocId)) {
        el.isEnable = true;
      }
    });
    nextTick(() => {
      changeState();
    });
    select_box.value = [];
    selectIds.value = [];
  });
};
const disable = () => {
  ElMessageBox.confirm('确定禁用所选数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    pocData.value.forEach((el: any) => {
      if (selectIds.value.includes(el.pocId)) {
        el.isEnable = false;
        enableIds.value.splice(enableIds.value.indexOf(el.pocId), 1);
      }
    });
    nextTick(() => {
      changeState();
    });
    select_box.value = [];
    selectIds.value = [];
  });
};
const allEnable = () => {
  pocData.value.forEach((el: any) => (el.isEnable = true));
  enableIds.value = allPocIds.value;
};
const allDisable = () => {
  pocData.value.forEach((el: any) => (el.isEnable = false));
  enableIds.value = [];
};
const searchClick = () => {
  search.pageNumber = 1;
  getList();
};
const reset = () => {
  search = {
    pageSize: 10,
    pageNumber: 1,
    vul_id: null,
    name: null,
    tags: null,
  };
  getList();
};
const handleSizeChange = async (v) => {
  search.pageSize = v;
  await getList();
};
const handleCurrentChange = async (v) => {
  search.pageNumber = v;
  await getList();
  nextTick(() => {
    changeState();
  });
  if (enableIds.value.length) {
    pocData.value.forEach((el: any) => {
      if (enableIds.value.includes(el.pocId)) {
        el.isEnable = true;
      } else {
        el.isEnable = false;
      }
    });
  }
};
const getList = async () => {
  loading.value = true;
  const { code, data = {} } = await store.dispatch('api/getPocList', search);
  loading.value = false;
  if (code !== 0) {
    return;
  }
  pocData.value = data.list.map((item) => {
    return {
      ...item,
      isEnable: false,
    };
  });
  total.value = data.total;

  //一键启用
  if (enableIds.value.length == total.value) {
    pocData.value.forEach((el: any) => (el.isEnable = true));
  } else {
    pocData.value.forEach((el: any) => (el.isEnable = false));
  }

  if (props.selectedIds.length) {
    pocData.value.forEach((el: any) => {
      if (props.selectedIds.includes(el.pocId)) {
        el.isEnable = true;
      }
    });
  }
};
const getPocIds = async () => {
  const { code, data = [] } = await store.dispatch('api/getPocIds', search);
  if (code !== 0) {
    return;
  }
  allPocIds.value = data;
};
// 设置表格复选框选中状态
const changeState = () => {
  if (multipleTable.value) {
    if (selectIds.value.length) {
      for (let i = 0; i < pocData.value.length; i++) {
        if (selectIds.value.indexOf(pocData.value[i]['pocId']) >= 0) {
          multipleTable.value.toggleRowSelection(pocData.value[i], true);
        }
      }
    } else {
      for (let i = 0; i < pocData.value.length; i++) {
        multipleTable.value.toggleRowSelection(pocData.value[i], false);
      }
    }
  }
};
const switchChange = (val, row) => {
  const { pocId } = row;
  if (val) {
    enableIds.value.push(pocId);
  } else {
    enableIds.value.splice(enableIds.value.indexOf(pocId), 1);
  }
};
const confirm = async () => {
  enableIds.value = [...new Set(enableIds.value)];
  emit('confirm', enableIds.value);
  cancel();
};
</script>
<style lang="scss" scoped>
.tooltip-box {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
